var sys = require("util"),
my_http = require("http");
var url  = require('url');
var qs = require('querystring');
var _mysql = require('mysql');

var HOST = 'localhost';
var PORT = 3306;
var MYSQL_USER = 'uxperf';
var MYSQL_PASS = 'uxperf';
var DATABASE = 'uxperf';
var TABLE = 'datapkgs'; 		// oryginalna baza zawierajaca JSON
var TABLEAN = 'uxperfAN'; 		// baza do analizy pogrupowanych danych
var TABLE_DATA_AN = 'dataAN'; 


var mysql = _mysql.createClient({
    host: HOST,
    port: PORT,
    user: MYSQL_USER,
    password: MYSQL_PASS,
});

mysql.query('use ' + DATABASE);

// funkcja pobierajaca dane z bazy 
function getData(cb, parameter) {
  
  console.log('PARAMETER = ' + parameter);
  var data = [];  
  
  if (parameter.param == 'navigationStart') {
	  mysql.query(
		"select id,navigationStart from dataan where uxperfAN_id='41'",
		function selectCb(error, results, fields) {
		  if (error) {
			  console.log('GetData Error: ' + error.message);
			  mysql.end();
			  return;
		  }

		  for (var i in results) {
				var row = results[i];						// pojedynczy rekord
				data.push({id: row.id, day: row.navigationStart});
		  } 
		  
		  cb(data,parameter);
		  console.log('end');	
	  });
  }
  else if (parameter.param == 'totalNavLoadTime'){
	  mysql.query(
		"select id,(loadEventEnd - navigationStart) as totalNav " +
				"from dataan " +
			"where uxperfan_id = 41",
		function selectCb(error, results, fields) {
		  if (error) {
			  console.log('GetData Error: ' + error.message);
			  mysql.end();
			  return;
		  }

		  for (var i in results) {
				var row = results[i];						// pojedynczy rekord
				data.push({id: row.id, day: row.totalNav});
		  } 
		  
		  cb(data,parameter);
		  console.log('end');	
	  });
  }
};


/**/
my_http.createServer(function(request,response){

	if (request.method === "GET") {
		var url_parts = url.parse(request.url, true);
		var query = url_parts.query;
		console.log('QUERY ' + query.param); //{Object}
		
		response.writeHeader(200, {
			"Content-Type": "text/plain",
			"Access-Control-Allow-Origin" : '*'
		});		
		
		getData( function(res) {		
			console.log(res);		
			response.write(JSON.stringify(res));
			response.end();		
		}, query);	
		
	}
	else {
		console.log("POST"); 
	}
	
}).listen(8081);
sys.puts("Server Running on 8081");
